<template>
  <div class="mobile-frame">
    <div style="height: calc(100% - 54px)">
      <van-nav-bar>
        <template #title>
          <van-search label="出库 " left-icon="" v-model="qrcode_str" placeholder="扫描单码" @search="onSearch" />
        </template>
        <template #right> </template>
      </van-nav-bar>
      <div style="width: 100%; height: calc(100% - 42px); overflow: auto">
        <van-tabs v-model:active="active" swipeable>
          <van-tab title="表头" name="表头" class="tabpanel">
            <van-cell-group inset>
              <van-field label="业务类型" v-model="pick_group.type" />
              <van-field label="单号" v-model="pick_group.order" />
              <van-field label="条码" v-model="pick_group.qrcode" />
              <van-field label="备料员" v-model="pick_group.worker" />
              <van-field label="任务数" v-model="pick_group.taskcount" />
            </van-cell-group>
          </van-tab>
          <van-tab title="记录" class="tabpanel">
            <van-cell-group inset>
              <van-cell
                v-for="item in qrcode_scan"
                :key="item.qrcode"
                :title="item.material"
                :value="`使用：${item.useqty}/剩余${item.remainer_qty}`"
                :label="item.qrcode"
              />
            </van-cell-group>
          </van-tab>
          <van-tab
            v-for="item in pick_group.details"
            :key="item.bill_id"
            :badge="item._remainer_qty === 0 ? 'ok' : ''"
            :name="item.bill_id"
            :title="item.title"
            class="tabpanel"
          >
            <van-cell-group inset>
              <van-field label="单号" v-model="item.bill_id" />
              <van-field label="品名" v-model="item.materialname" />
              <van-field label="库位" v-model="item.loc" />
              <van-field label="可备货数" v-model.number="item._remainer_qty" />
              <van-field label="本轮备货" v-model.number="item.process_qty" />
              <van-field label="库存预留" v-model.number="item._stock_reserv_qty" />
              <van-field label="需求数" v-model.number="item.all_qty" />
              <van-field label="已发料" v-model.number="item.stock_qty" />
              <van-field label="预留信息" v-model="item.reservinfo" />
              <van-field label="叫料单号" v-model="item.bill_id" />
            </van-cell-group>
          </van-tab>
        </van-tabs>
      </div>
      <van-button :disabled="qrcode_scan.length === 0" @click="submit" type="primary" block>提交</van-button>
    </div>
  </div>
</template>
<script lang="ts" setup>
import { useDbStore } from '@/stores/modules/database'
import { ref } from 'vue'
import { showDialog } from 'vant'
import { distinct, fill_ref_info, get_code_prefix, make_billcode } from '@/utils/common'
import { e_call_status, e_code_prefix, e_pick_status, e_require_order_status } from '@/types/enum'
import type { pd_qrcode } from '@/types/producedata'
import { erase_reserv_for_stock, get_reserv_from_order, type t_reserv_info } from '@/utils/reservHelper'
import type { pick_record } from '@/types/billdata'

interface t_pick_d {
  title: string
  bill_id: string
  order_id: string
  material: string
  materialname: string
  all_qty: number
  stock_qty: number
  order_reserv_qty: number
  stock_reserv_qty: number //库存预留数
  all_reserv_qty: number //订单+库存预留数
  remainer_qty: number //剩余数，allqty-stockqty
  _stock_reserv_qty: number //本轮动态预留数(库存)
  _remainer_qty: number //本轮动态剩余数
  process_qty: number //本次临时处理的未提交数
  loc: string
  qrcodes: { qrcode: string; qty: number }[]
  reserv?: t_reserv_info
  reservinfo: string
}
interface t_pickgroup {
  order: string
  type: string
  qrcode: string
  worker: string
  taskcount: number
  details: t_pick_d[]
}
type t_scan_record = { qrcode: string; material: string; useqty: number; remainer_qty: number }
const db = useDbStore()
const qrcode_scan = ref<t_scan_record[]>([])
const active = ref<string>('表头')
const qrcode_str = ref<string>()
const pick_records: pick_record[] = []
const pick_group = ref<t_pickgroup>({
  type: '',
  qrcode: '',
  order: '',
  worker: '',
  taskcount: 0,
  details: []
})
const clearQrDoc = () => {
  pick_group.value = {
    type: '',
    qrcode: '',
    order: '',
    taskcount: 0,
    worker: '',
    details: []
  }
  active.value = '表头'
  qrcode_scan.value = []
}
const onSearch = () => {
  const type = get_code_prefix(qrcode_str.value!)
  const content = trimPrefix(qrcode_str.value!)
  qrcode_str.value = ''
  switch (e_code_prefix[type as keyof typeof e_code_prefix]) {
    case e_code_prefix.拣货单:
      clearQrDoc()
      pick_group.value.type = type
      pick_group.value.qrcode = qrcode_str.value!
      searchBill(content)
      break
    case e_code_prefix.拣货单行:
      clearQrDoc()
      pick_group.value.type = type
      pick_group.value.qrcode = qrcode_str.value!
      searchRow(content)
      break
    case e_code_prefix.物码:
      searchQr(content)
      break
  }
}
const trimPrefix = (str: string) => {
  const indexOf = str.indexOf('#')
  return str.substring(indexOf + 1, str.length)
}
const formatReserv = (info?: t_reserv_info) => {
  if (!info) return '无预留'
  let str = ''
  info.t.forEach((r) => {
    str += `${r.type}预留${r.qty},`
  })
  return str
}
const searchBill = (key: string) => {
  pick_group.value.qrcode = qrcode_str.value!
  const bill = db.pick.find((r) => r.billcode === key && r.status === e_pick_status.发放)
  if (!bill) {
    showDialog({ title: '错误', message: '找不到单据' })
    return
  }
  pick_group.value.order = key
  pick_group.value.taskcount = bill.call_count
  pick_group.value.worker = bill.worker
  const call = db.mtl_call.filter((r) => r.pick === key && r.call_qty - r.stockout_qty > 0)

  const detail: t_pick_d[] = []
  call.forEach((r) => {
    const materialdoc = typeof r.material === 'string' ? db.material.find((s) => s.code === r.material)! : r.material
    const loc = db.qrcode
      .filter((r) => (typeof r.material === 'string' ? r.material : r.material.code) === materialdoc.code)
      .map((r) => {
        return typeof r.location === 'string' ? r.location : r.location.code
      })
    const d_loc = distinct(loc).join(',')
    const reserv_info = get_reserv_from_order(r.srcbill)

    detail.push({
      title: materialdoc.code,
      bill_id: r.billcode,
      material: materialdoc.code,
      materialname: materialdoc.name,
      all_qty: r.call_qty,
      stock_qty: r.stockout_qty,
      remainer_qty: r.call_qty - r.stockout_qty,
      _remainer_qty: r.call_qty - r.stockout_qty,
      process_qty: 0,
      loc: d_loc,
      order_id: r.srcbill,
      reserv: reserv_info,
      qrcodes: [],
      reservinfo: formatReserv(reserv_info),
      stock_reserv_qty: reserv_info?.t.find((r) => r.type === '库存')?.qty || 0,
      order_reserv_qty: reserv_info?.t.find((r) => r.type !== '库存')?.qty || 0,
      all_reserv_qty: reserv_info?.h || 0,
      _stock_reserv_qty: reserv_info?.t.find((r) => r.type === '库存')?.qty || 0
    })
  })
  pick_group.value.details = detail
}
const searchRow = (key: string) => {
  const bill = db.mtl_call.find(
    (r) => r.billcode === key && (r.status === e_call_status.正在拣货 || r.status === e_call_status.已下派)
  )
  if (!bill) {
    showDialog({ title: '错误', message: '找不到单据' })
    return
  }
  searchBill(bill.pick!)
  pick_group.value.details = pick_group.value.details.filter((r) => r.bill_id === key)
}

const searchQr = (key: string) => {
  if (pick_group.value.details.length === 0) {
    showDialog({ title: '错误', message: '先扫单码' })
    return
  }
  const qrcode = db.qrcode.find((r) => r.qrcode === key)
  if (!qrcode) {
    showDialog({ title: '错误', message: '找不到这个条码的信息' })
    return
  }
  const exist_scan = qrcode_scan.value.find((r) => r.qrcode === key)
  if (exist_scan) {
    showDialog({ title: '错误', message: '这个条码已经被扫过' })
    return
  }
  const materialcode = typeof qrcode.material === 'string' ? qrcode.material : qrcode.material.code
  const matchs = pick_group.value.details.filter((r) => r.material === materialcode && r.remainer_qty > 0)
  if (matchs.length === 0) {
    showDialog({ title: '错误', message: '这个条码不是本单要出库的物料或需求已经被满足' })
    return
  }
  let qrcode_qty = qrcode.qty
  const scan: t_scan_record = { qrcode: qrcode.qrcode, material: materialcode, useqty: 0, remainer_qty: qrcode.qty }
  matchs.forEach((r) => {
    const reserv_by_order = r.reserv?.t.find((t) => t.type !== '库存')?.qty || 0
    let need_to_pick = r.remainer_qty - reserv_by_order
    if (need_to_pick <= 0) return
    const use_qty = r.remainer_qty - r.order_reserv_qty - r.process_qty
    const q = Math.min(use_qty, qrcode_qty)
    r.process_qty += q
    r._remainer_qty -= q
    r._stock_reserv_qty -= Math.min(q, r._stock_reserv_qty)
    if (q !== 0) {
      r.qrcodes.push({ qrcode: qrcode.qrcode, qty: q })
      scan.remainer_qty -= q
      scan.useqty += q
      qrcode_qty -= q
      active.value = r.bill_id
      pick_records.push({ qrcode: qrcode.qrcode, qty: q, call_id: r.bill_id })
    }
    if (scan.useqty > 0) showDialog({ title: '提示', message: `成功备货${scan.useqty}个` })
    else showDialog({ title: '错误', message: `备货失败` })
  })
  if (scan.useqty > 0) qrcode_scan.value.push(scan)
}
const submit = () => {
  pick_group.value.details.forEach((r) => {
    const bill = db.mtl_call.find((s) => s.billcode === r.bill_id)!
    bill.pick_qty += r.process_qty
    if (bill.pick_qty > 0) bill.status = e_call_status.正在拣货
    if (bill.pick_qty >= bill.call_qty) bill.status = e_call_status.拣货完成
    const release_reserv = 0 - (r.stock_reserv_qty - r._stock_reserv_qty)
    db.reservMaterialStock(r.material, release_reserv)
    erase_reserv_for_stock(r.order_id, 0 - release_reserv)
    db.require_order.find((t) => t.billcode === r.order_id)!.locked_qty += r.process_qty
    db.lockMaterialStock(r.material, r.process_qty)
  })
  qrcode_scan.value.forEach((r) => {
    db.qrcode.find((s) => s.qrcode === r.qrcode)!.qty -= r.useqty
  })
  pick_records.forEach((r) => {
    db.pick_record.push(r)
  })
  db.savePickRecord()
  db.saveQrCode()
  db.saveMtlCall()
  db.saveRequireOrder()
  clearQrDoc()
  showDialog({ title: '提示', message: '提交成功' })
}
</script>
<style>
.tabpanel {
  padding-top: 10px;
}
</style>
